package com.yeook.ymax.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import com.yeook.ymax.db.databasecreator.Column;
import com.yeook.ymax.db.databasecreator.Column.SQLiteType;
import com.yeook.ymax.db.databasecreator.TableCreator;
import com.yeook.ymax.utils.ZipUtils;

public class DbStructure  extends SQLiteOpenHelper {
	
	public final static String TABLE_WALLPAPER = "table_wallpaper";
	public final static String TABLE_HASHES = "table_hashes";
	public final static String TABLE_HISTORY = "table_history";
	public final static String TABLE_RINGTONE = "table_ringtone"; 
	
	public final static String COLUMN_ID = "_id";
	public final static String COLUMN_DWN = "dwn";
	public final static String COLUMN_DESCRIPTION = "description";
	public final static String COLUMN_UNIQUER_ID = "uniqueId";
	public final static String COLUMN_LABLE = "lable";
	public final static String COLUMN_FILE_NAME = "fileName";
	public final static String COLUMN_CATE_CODE = "cateCode";
	public final static String COLUMN_FAVORITE = "favorite";
	public final static String COLUMN_TYPE = "type";
	public final static String COLUMN_DATE = "date";
	public final static String COLUMN_ATTACHMENTID = "attachmentId";
	public final static String COLUMN_TAGS = "tags";
	
	public final static String COLUMN_HASH = "hash";
	
	private static String DB_PATH = "/data/data/com.yeook.ymax/databases/";

	private static String DB_NAME = "ymax.db";
	private static String ZIP_NAME = "ymax.zip";
	private SQLiteDatabase mDb;
	
	private Context mcontext = null;

	public DbStructure(Context context) {
		super(context, DB_NAME, null, 9);
		mcontext = context;
	}
	
	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
		} else {

			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			this.getReadableDatabase();

			try {

				copyDataBase();

			} catch (IOException e) {

				throw new Error("Error copying database");

			}
		}

	}
	
	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = mcontext.getAssets().open(ZIP_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + ZIP_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
		
		File zipFile = new File(outFileName);
		//解压文件
		ZipUtils.upZipFile(zipFile, DB_PATH);
		//解压完文件之后把压缩文件删除
		zipFile.delete();

	}
	
	public SQLiteDatabase openDataBase() throws SQLException {

		// Open the database
		String myPath = DB_PATH + DB_NAME;
		mDb = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
		
		return mDb;

	}
	
	@Override
	public synchronized void close() {

		if (mDb != null && mDb.isOpen()){
			mDb.close();
		}

		super.close();

	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {

			// database does't exist yet.

		}

		if (checkDB != null) {

			checkDB.close();

		}

		return checkDB != null ? true : false;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		TableCreator creator = new TableCreator(db);
		creator.newTable(TABLE_WALLPAPER).addColumn(new Column(SQLiteType.INTEGER, COLUMN_ID).setPrimaryKey())
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_DWN))
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_FAVORITE))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_DESCRIPTION))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_UNIQUER_ID))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_ATTACHMENTID))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_LABLE))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_FILE_NAME))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_DATE))
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_CATE_CODE)).createTable();
		
		creator.newTable(TABLE_HASHES).addColumn(new Column(SQLiteType.TEXT, COLUMN_HASH).setPrimaryKey())
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_TYPE))
		.createTable();
		
		creator.newTable(TABLE_HISTORY).addColumn(new Column(SQLiteType.INTEGER, COLUMN_ID).setPrimaryKey())
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_UNIQUER_ID))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_TYPE))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_DATE))
		.createTable();
		
		creator.newTable(TABLE_RINGTONE).addColumn(new Column(SQLiteType.INTEGER, COLUMN_ID).setPrimaryKey())
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_DWN))
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_FAVORITE))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_DESCRIPTION))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_UNIQUER_ID))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_TAGS))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_LABLE))
		.addColumn(new Column(SQLiteType.TEXT, COLUMN_FILE_NAME))
		.addColumn(new Column(SQLiteType.LONG, COLUMN_DATE))
		.addColumn(new Column(SQLiteType.INTEGER, COLUMN_CATE_CODE)).createTable();
		
		db.execSQL("CREATE INDEX table_wallpaper_uniqueId ON table_wallpaper(uniqueId);");
		db.execSQL("CREATE INDEX table_ringtone_uniqueId ON table_ringtone(uniqueId);");
		db.execSQL("CREATE INDEX table_history_uniqueId ON table_history(uniqueId);");
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_WALLPAPER);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_RINGTONE);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_HASHES);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
	}

}
